<template>
  <Form
    ref="fm"
    :validation-schema="mySchema"
    v-slot="{ errors }"
    class="xtx-form"
  >
    <!-- 测试 -->
    <!-- <p>{{ errors }}</p> -->
    <!-- 展示=》上一步腾讯服务器QQ登陆成功的账号信息 -->
    <div class="user-info">
      <img :src="qqUserInfo.pic" alt="" />
      <p>
        Hi，{{ qqUserInfo.nickname }}
        欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~
      </p>
    </div>
    <!-- 绑定QQ号 -->
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          name="mobile"
          v-model="formData.mobile"
          class="input"
          :class="{ err: errors.mobile }"
          type="text"
          placeholder="绑定的手机号"
        />
      </div>
      <!-- 展示出错信息 -->
      <div v-show="errors.mobile" class="error">{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          name="code"
          v-model="formData.code"
          class="input"
          :class="{ err: errors.code }"
          type="text"
          placeholder="短信验证码"
        />
        <span class="code" @click="send">{{
          count === 0 ? "发送验证码" : `${count}秒后发送`
        }}</span>
      </div>
      <div v-show="errors.code" class="error">{{ errors.code }}</div>
    </div>
    <a href="javascript:;" class="submit" @click="bindQQ">立即绑定</a>
  </Form>
</template>

<script>
import { ref, reactive } from 'vue'
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import Message from '@/components/Message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
// 导入发短信钩子方法
import { useSendCode } from '@/hook/page'
//  获取登录成功QQ账号信息
const useGetQQInfo = () => {
  const qqUserInfo = ref({})
  window.QC.Login.check() && window.QC.api('get_user_info').success(({ data }) => {
    console.log('qq user:', data)
    qqUserInfo.value.nickname = data.nickname
    qqUserInfo.value.pic = data.figureurl_1
  })
  return { qqUserInfo }
}
// 校验QQ绑定表单
const useValidForm = () => {
  /**
   * 思路：
   * 1. 定义表单数据
   * 2. 定义校验函数
   */
  const formData = reactive({
    mobile: '',
    code: ''
  })
  const mySchema = {
    mobile: schema.mobile,
    code: schema.code
  }
  return { formData, mySchema }
}

export default {
  name: 'CallbackBind',
  components: {
    Form, Field
  },
  props: {
    openId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    // 定义form组件实例
    const fm = ref()
    const store = useStore()
    const router = useRouter()
    // 获取qq用户信息
    const { qqUserInfo } = useGetQQInfo()
    // 表单校验
    const { formData, mySchema } = useValidForm()

    // 发送验证码
    const { count, send } = useSendCode(formData, fm, userQQBindCode)

    // 提交绑定QQ
    const bindQQ = async () => {
      // 表单整体校验=》1. 给Form组件绑定ref 2. 通过ref获取Form组件实例=》fm.value.validate()
      const res = await fm.value.validate()
      // console.log(res)
      if (res.valid) {
        // 校验通过=》调用接口绑定QQ
        try {
          const res = await userQQBindLogin({ unionId: props.openId, ...formData })
          /**
           * 登陆成功存储qq登录人的信息
           */
          store.commit('user/updateProfile', res.result)
          Message({ type: 'success', text: 'QQ登录成功！' })
          router.replace('/')
        } catch (error) {
          Message({ type: 'error', text: 'QQ绑定失败！' })
        }
      }
    }
    return { qqUserInfo, formData, mySchema, bindQQ, fm, count, send }
  }
}
</script>

<style scoped lang='less'>
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
